CROSS_COMPILE ?= x86_64-linux-musl-

STATIC = ×
TARGET = $(shell ${CROSS_COMPILE}gcc -dumpmachine)
GIT_VERSION = $(shell git rev-parse --short HEAD)

PROJECT_NAME = loglua
OBJ_DIR      = objs/$(TARGET)
TARGET_DIR   = bin/$(TARGET)

C_SRCS = hv/hv.c
CPP_SRCS = hv/hstring.cpp hv/hurl.cpp hv/iniparser.cpp\
    efsw/Debug.cpp efsw/DirectorySnapshot.cpp efsw/DirectorySnapshotDiff.cpp \
    efsw/DirWatcherGeneric.cpp efsw/FileInfo.cpp efsw/FileSystem.cpp efsw/FileWatcher.cpp \
    efsw/FileWatcherCWrapper.cpp efsw/FileWatcherFSEvents.cpp efsw/FileWatcherGeneric.cpp \
    efsw/FileWatcherImpl.cpp efsw/FileWatcherInotify.cpp efsw/FileWatcherKqueue.cpp \
    efsw/FileWatcherWin32.cpp efsw/Log.cpp efsw/Mutex.cpp efsw/String.cpp efsw/System.cpp \
    efsw/Thread.cpp efsw/Watcher.cpp efsw/WatcherFSEvents.cpp efsw/WatcherGeneric.cpp \
    efsw/WatcherInotify.cpp efsw/WatcherKqueue.cpp efsw/WatcherWin32.cpp \
    efsw/platform/posix/FileSystemImpl.cpp efsw/platform/posix/MutexImpl.cpp \
    efsw/platform/posix/SystemImpl.cpp efsw/platform/posix/ThreadImpl.cpp \
    lua/blua.cpp lua/lua_filewatcher.cpp lua/lua_log.cpp lua/lua_network.cpp \
    loglua.cpp
PROJECT_OBJS = $(patsubst  %.cpp, $(OBJ_DIR)/%.o, $(notdir $(CPP_SRCS))) \
               $(patsubst  %.c,   $(OBJ_DIR)/%.o, $(notdir $(C_SRCS)))

CC  = $(CCACHE) $(CROSS_COMPILE)gcc
CXX = $(CCACHE) $(CROSS_COMPILE)g++

CFLAGS  = -Os -fstack-protector -ffunction-sections -fdata-sections
LDFLAGS = -Os -s

ifeq ($(findstring -musl,"$(CROSS_COMPILE)"), -musl)
C_FLAGS += -static
endif

C_FLAGS += $(CFLAGS) -Wall -Wno-shift-count-overflow -Wno-unused-label -Wno-unused-result -Wno-unused-variable -Wno-unused-function -Wno-unused-but-set-variable -Wno-format-truncation -Wno-maybe-uninitialized
C_FLAGS += -DNDEBUG
C_FLAGS += -I$(HOME)/libs/$(subst -none,,$(TARGET)) -I. -Iinclude -Iinclude/hv -I3rd

CXX_FLAGS += -std=c++17 -Wno-psabi $(C_FLAGS)

LD_FLAGS += $(LDFLAGS) -Wl,--gc-sections -Wl,--allow-multiple-definition
LD_FLAGS += -L$(HOME)/libs/$(subst -none,,$(TARGET)) -llua -pthread -lstdc++ -lm

ifeq ($(findstring -static,"$(C_FLAGS)"), -static)
LD_FLAGS += -static
STATIC = ✓
endif

vpath %.c   $(dir $(C_SRCS))
vpath %.cpp $(dir $(CPP_SRCS))

.PHONY: all clean
default: all

all: $(PROJECT_NAME)

prepare:
	@mkdir -p $(OBJ_DIR)
	@mkdir -p $(TARGET_DIR)
	@echo "#define GIT_VERSION \"$(GIT_VERSION)\"" > ver_git.h

$(OBJ_DIR)/%.o: %.cpp prepare
	@printf "    CXX $< \n"
	@$(CXX) $(CXX_FLAGS) -o $@ -c $<

$(OBJ_DIR)/%.o: %.c prepare
	@printf "    CC  $< \n"
	@$(CC) $(C_FLAGS) -o $@ -c $<

$(PROJECT_NAME): $(PROJECT_OBJS)
	@printf "    LD  $(PROJECT_NAME)\n"
	@$(CC) -o $(TARGET_DIR)/$@ $^ $(LD_FLAGS)
	@cp ./loglua.lua $(TARGET_DIR)
	@cp -r scripts $(TARGET_DIR)
	@printf "    make all done. \n"

clean:
	@$(RM) $(OBJ_DIR)/*
	@$(RM) $(TARGET_DIR)/*
	@printf "    🦀 make clean done.\n"
